package myCache

import (
	"fmt"
	"github.com/gogf/gcache-adapter/adapter"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gcache"
	"github.com/gogf/gf/util/gconv"
	"time"
)

// GetOrSetFunc 缓存，值存入Redis时是通过json格式存储的，所以取出需要转换一下
func GetOrSetFunc(key interface{}, f func() (interface{}, error), duration time.Duration) (interface{}, error) {
	c := gcache.New()
	c.SetAdapter(adapter.NewRedis(g.Redis()))
	return c.GetOrSetFunc(key, f, duration)
}

func Set(key interface{}, value interface{}, duration time.Duration) error {
	c := gcache.New()
	c.SetAdapter(adapter.NewRedis(g.Redis()))
	return c.Set(key, value, duration)
}

func Get(key interface{}) (interface{}, error) {
	c := gcache.New()
	c.SetAdapter(adapter.NewRedis(g.Redis()))
	return c.Get(key)
}

func Delete(key interface{}) {
	c := gcache.New()
	c.SetAdapter(adapter.NewRedis(g.Redis()))
	c.Remove(key)
}

// GetAdminCaches 获取管理员缓存
func GetAdminCaches(adminId string) []string {
	return g.ArrayStr{
		"adminCache:model:" + adminId,      // 权限
		"adminCache:depaName:" + adminId,   // 菜单
		"adminCache:perms:" + adminId,      // 部门名称
		"adminCache:menu:" + adminId,       // 角色
		"adminCache:roleIdList:" + adminId, // 单条信息
	}
}

// ClaerAdminCaches 清除管理员缓存
func ClaerAdminCaches(adminId string) {
	fmt.Println("ClaerAdminCaches  ", GetAdminCaches(adminId))
	ClaerCaches(gconv.Interfaces(GetAdminCaches(adminId))...)
	/*_, err := g.DB().GetCache().Remove(gconv.Interfaces(GetAdminCaches(adminId))...)
	if err != nil {
		fmt.Println(err)
		return
	}*/
}

func ClaerCaches(keys ...interface{}) {
	fmt.Println("ClaerCaches  ", keys)
	_, err := g.DB().GetCache().Remove(keys...)
	if err != nil {
		fmt.Println(err)
		return
	}
}
